<?php 

//底部导航
function bottom_menu(){
	$result = M('Navi')->where('status = 1 and type = 2 and parent_id = 0')->select();
	//组装下级导航
	if(!empty($result)){
		foreach($result as $k=>$v){
			$item = M('Navi')->where('status = 1 and type = 2 and parent_id = %d',$v['id'])->select();
			$result[$k]['item'] = $item;
		}
	}
	return $result;
}

//记录访问数
function flow_data($aid){
	//当前url
	$url='http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
	$ip = get_client_ip();
	$data=array(
		'ip_location'=>$ip,
		'aid'=>$aid,	
		'url'=>$url,
		'createtime'=>NOW_TIME,
	);
	//查询是否有相同的ip,aid,uid,是就浏览数不加一
	M('ArticleFlow')->add($data);
	//访问数+1
	M('Article')->where('id = %d and uid =  %d',$aid,$uid)->setInc('views');
}

//模拟header头，用于curl抓取
     function wx_header(){
		$header = array(
            'Accept'=>'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'User-Agent'=>'Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5',
            'Accept-Encoding'=>'gzip, deflate, sdch',
            'Accept-Language'=>'zh-CN,zh;q=0.8',
            'Cache-Control'=>'max-age=0',
            'Connection'=>'keep-alive',
            'Host'=>'mmbiz.qpic.cn'
        );
		return $header;
	}



//抓取文章(暂时微信文章)
function file_put_wx($url){
	$contents = file_put_http_article($url);
	$contents = explode('js_article', $contents);
	$contents = $contents[1];
	$contents = explode('<script>window.moon_map', $contents);
	$contents = $contents[0];
	$contents = '<div id="js_article'.$contents;
	return $contents;
}



//抓取文章
function file_put_article($url,$pattern, $ua){

	if(strpos($url,'mp.weixin.qq.com') !== false || strpos($url,$_SERVER['HTTP_HOST']) !== false){
		//抓取微信文章
		$content = file_put_wx($url);
	}else{
		
		$html_content = file_put_http_article($url, $ua);
		preg_match_all($pattern,$html_content,$match);
		$content = "";
		foreach($match as $k=>$v){
			foreach($v as $vv){
				$content.=$vv;
			}
		}

		
	}
	return $content;
}

//抓取http文章内容
function file_put_http_article($url, $ua){
	$header = wx_header();
	/*$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //如果把这行注释掉的话，就会直接输出
	$contents=curl_exec($ch);
	curl_close($ch);*/
	$curl = new  \Org\Util\Curl;
	if($ua){
		$extra = array('CURLOPT_USERAGENT'=>$ua);	
	}
	$contents = $curl->ihttp_request($url, null, $extra);
	$content = $contents['content'];
	
	//寻找不到的时候，使用file_get_contents进行获取
	if(empty($content)){
		$content = file_get_contents($url);
	}

	$search = array(
        '@<script[^>]*?>.*?</script>@si',  // Strip out javascript
        //'@<![\s\S]*?--[ \t\n\r]*>@',         // Strip multi-line comments including CDATA
      
	);
	$content = preg_replace($search, '', $content);

	return $content;
}






//文章内容提交替换
function replace_content($content){
	//截取文章
	$position_attr = strpos($content,'content=');
	$content  = substr($content,$position_attr+8);
	$position_attr = 0;
	$position_attr = strrpos($content,'&title=');
	$content  = substr($content,0,$position_attr);
	
	//替换链接
	$content = str_replace('data-href','href',$content);
	$content = str_replace('css_background','',$content);
	$content = str_replace('margin-left:-10px','margin-left:0px',$content);
	$content = str_replace('提示：点击这里开始编辑','',$content); //替换自建文章的文字
	return $content;
}

//发送邮箱
/*
*@send_mail string 字符串 以;区分
*@addressuser  string 发件人名称
*@title     string 文章标题
*@content   string 内容
*/

function send_mail($send_mail,$addressuser="发件人名称",$title = '支付宝提现',$content = 'xxx提现'){
	if(!empty($send_mail)){
		//发送邮箱
		$mail_array = explode(';',$send_mail);
		if(!empty($mail_array)){
			foreach($mail_array as $k=>$v){
				if(!empty($v)){
					sendMail($v,$addressuser,$title,$content);
				}
			}
		}
	}
}


/*
 *判断非会员是否有试用期
 *@param array $option 系统设置
 *@param array $fans   会员信息
 *@param bool  $display 是否返回天数
 *@param bool  
 */
function judge_member_probation($option,$fans,$display = false){

	if(empty($option['probation']) || empty($fans) || $fans['level'] == 1){
		return false;
	}
	$probation   = $option['probation']; //系统设置的试用天数

    $day_time    = 86400 * $probation;  //系统设置的试用天数时间戳

    $now_member  = M('User')->where(array('id'=>$fans['id']))->getField('createtime'); //当前会员的注册时间

    /*-----不使用session存储的 会员创建时间----*/
	//$now_member  = $fans['createtime']; 
	$member_time = $now_member + $day_time; //会员使用时间戳
	
	if(NOW_TIME > $member_time){
		return false;
	}else{
		if($display){
			$day = ceil(abs((NOW_TIME - $member_time) / 86400));
			return $day;
		}else{
			return true;
		}
	}
}


/*
	抓取图片到本地
*/
function get_article_img($url,$filename='',$type='jpg'){
	
    if($url==''){return false;}
	//$file = './resource/attachment/avatar';
	$file =  C('upload_path').'/temporary';
	
    if($filename==''){
        $ext=strrchr($url,'.');
        if($ext !='.gif' && $ext !='.jpg'){
        	return false;
        }
        $filename=time().$ext;
    }
    //文件保存路径 
   
	$ch=curl_init();
	$timeout=100;
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
	$img=curl_exec($ch);
	curl_close($ch);
    $size=strlen($img);
	if($size == 0){ //0 为没有任何内容的图片
		return false;
	}
	//创建目录
	$year  = date('Y');
	$month = date('m');
	$rdate = date('d');
	if(!is_dir($file.'/'.$year)) {
		mkdir($file.'/'.$year, 0777, true);
	}
	if(!is_dir($file.'/'.$year.'/'.$month)) {
		mkdir($file.'/'.$year.'/'.$month, 0777, true);
	}
	if(!is_dir($file.'/'.$year.'/'.$month.'/'.$rdate)) {
		mkdir($file.'/'.$year.'/'.$month.'/'.$rdate, 0777, true);
	}
	

	$fp2=@fopen($file.'/'.$year.'/'.$month.'/'.$rdate.'/'.$filename.'.'.$type,'w');
	fwrite($fp2,$img);
	fclose($fp2);
	
	$array[0] = $file.'/'.$year.'/'.$month.'/'.$rdate.'/'.$filename.'.'.$type;
	
	import('Vendor.photoCompression.photo');
	if($type != 'gif'){
		//压缩图片
		imagezoom($array[0],$array[0],'#ffffff');
	}
	
    return $array;
}


/**
 * 用于获取公众号的js
 * 
 */
function wx_share(){
	$weixin_array = M('Options')->where("option_name = 'weixin_array'")->find();
	$weixin_array = unserialize($weixin_array['option_value']);	
	$appid = $weixin_array['appid'];
	
	import('Vendor.Wechat.access');
	$wechat = new \WechatAccess();
	$jsapiTicket = $wechat->account_jsapi();

	if($jsapiTicket){
		$url = "http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
		$timestamp = NOW_TIME;
		$nonceStr = random(16);
		
		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
		$signature = sha1($string);
		$signPackage = array(
		  "appId"     => $appid,
		  "nonceStr"  => $nonceStr,
		  "timestamp" => $timestamp,
		  "url"       => $url,
		  "signature" => $signature,
		  "rawString" => $string
		);
		$jsapi = $signPackage;

	}

	return $jsapi;
}




